module SpiceInit
  module Module
    def modinit(options={})
      track_spices = options.has_key?(:track_spices) ? options.delete(:track_spices) : false
      
      options.each do |key,value|

        match = key.to_s.match(/([\!\?]$)/)
        if match
          setter = var = match.pre_match
          getter = setter + match[1]
        else
          setter = getter = var = key
        end
        module_eval %Q{

          def self.#{getter}(*args)
            if @@#{var}.is_a?(Proc)
              @@#{var}.call(*args)
            else
              @@#{var}
            end
          rescue
            raise ArgumentError
              caller
          end

          def self.#{setter}=(value)
            @@#{var} = value
          end
        }
        class_variable_set("@@#{var}",value)
        if track_spices
          unless respond_to?(:spices_added)
            module_eval %Q{
              def self.spices_added
                @@_spices_added
              end
            }
            class_variable_set("@@_spices_added",[])
          end
          spices_added << "#{setter}="  unless spices_added.include?("#{setter}=")
          spices_added << "#{getter}"   unless spices_added.include?("#{getter}")
        end
      end
    end
    alias_method :clasinit, :modinit
    alias_method :modspice, :modinit
    alias_method :claspice, :modinit
  end
end
